package com.liuyucheng.swing.component;

import com.liuyucheng.idea_springboot.util.IOUtil;

import javax.swing.*;
import java.awt.*;
import java.io.*;

/**
 * 图片面板
 *
 * @author LiuYuCheng
 * @date 2021年12月24日 17:27
 */
public class ImagePanel extends JPanel {
    private ImageIcon icon;
    private Image img;

    private static final String filePath = System.getProperty("user.home")+ File.separator+"bg.jpg";

    public ImagePanel() throws FileNotFoundException {
        //  /img/HomeImg.jpg 是存放在你正在编写的项目的bin文件夹下的img文件夹下的一个图片
        InputStream inputStream = new FileInputStream(filePath);
        byte[] bytes = new byte[0];
        try {
            bytes = IOUtil.read(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        icon = new ImageIcon(bytes);
        img = icon.getImage();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        //下面这行是为了背景图片可以跟随窗口自行调整大小，可以自己设置成固定大小
        g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
    }

    public static void main(String[] args) throws FileNotFoundException {
        JFrame frame = new JFrame("");
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(600,400);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);

        ImagePanel rootPanel = new ImagePanel();
        frame.setContentPane(rootPanel);
        rootPanel.setLayout(null);
        rootPanel.repaint();
    }
}
